<template>
  <div class="paper-detail">
    <div v-loading="loading" class="paper-right">
      <div class="tools-bar">
        <el-row> </el-row>
        <el-row>
          <!-- <el-button icon="el-icon-plus" @click="openProblem">题库选题</el-button>
          <el-button type="primary" icon="el-icon-printer" @click="savePaper">保存试卷</el-button> -->
          <el-button type="primary" icon="el-icon-download" @click="downloadPaper">下载试卷</el-button>
          <el-button type="primary" icon="el-icon-download" @click="downloadAnswer">下载答案</el-button>
        </el-row>
      </div>
      <div class="paper-content">
        <div class="paper-view">
          <div class="paper-title">题目列表</div>
          <div class="paper-body">
            <PaperContent
              v-if="paperData.length > 0"
              ref="paperContent"
              :paper-detail="paperDetail"
              :paper-data="paperData"
              :is-view="isView"
              @changeSelection="changeSelection"
              @checkHeader="checkHeader"
              @edit="handleEdit"
              @moveUp="handleMoveUp"
              @moveDown="handleMoveDown"
              @delete="handleDelete"
            />

            <template v-else>
              <el-empty v-if="!loading" description="请选择题目">
                <el-button icon="el-icon-plus" @click="openProblem">题库选题</el-button>
              </el-empty>
            </template>
          </div>
        </div>
        <div class="paper-attr">
          <div class="paper-title">试题详情</div>
          <div class="paper-body" :class="{ 'not-click': isView === true }">
            <PaperAttr :paper-type="paperType" :paper-data="attrData" @changeQuestion="changeQuestionAttr" @changePaper="changePaperAttr" />
          </div>
        </div>
      </div>
    </div>

    <PaperProblem ref="paperProblem" @confirm="confirmPaper" />
    <EditDialog ref="editDialog" @confirm="confirmEditQuestion" />
  </div>
</template>
<script>
import PaperContent from "./content";
import PaperProblem from "./problem";
import PaperAttr from "./attr";
import EditDialog from "./editDialog";
import { addJuanPaper, getJuanPaperBakeup, updateJuanPaper } from "@/api/juan/juanPaper";
import { getBakeupQuestionById } from "@/api/juan/juanQuestion";
import { guid } from "@/utils";

export default {
  components: { PaperContent, PaperProblem, PaperAttr, EditDialog },
  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
    isView: {
      type: Boolean,
      default: false,
    },
  },
  dicts: ["topic_type", "difficulty"],
  data() {
    return {
      paperId: null,
      paperDetail: null,
      paperData: [],
      loading: false,
      attrData: null,
      paperType: "",
      cascader: {},
    };
  },
  computed: {
    cascader_info() {
      return JSON.parse(localStorage.getItem("leftPanel"));
    },
  },
  watch: {
    cascader_info: {
      handler(val) {
        if (val) {
          this.cascader = val;
        }
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    if (this.isEdit) {
      this.paperId = this.$route.query.paperId;
      if (this.paperId) {
        this.fetchData();
      } else {
        this.$router.go(-1);
      }
    } else {
      this.paperDetail = {
        paperName: "试卷名称",
        paperTime: 120,
        paperTotalScore: 0,
        paperAttention: "",
      };
      this.paperData = [];
    }
  },
  methods: {
    fetchData() {
      this.loading = true;
      getJuanPaperBakeup(this.paperId)
        .then((res) => {
          this.paperDetail = res.data;
          let paperQuestionInfoStr = res.data.paperQuestionInfo;
          let paperQuestionInfo = [];
          try {
            paperQuestionInfo = JSON.parse(paperQuestionInfoStr);
          } catch (error) {
            paperQuestionInfo = [];
          }

          let questionIds = [];
          paperQuestionInfo.forEach((item) => {
            if (item.questions.length > 0) {
              let ids = item.questions.map((cItem) => {
                return cItem.questionId;
              });
              questionIds.push(...ids);
            }
          });

          getBakeupQuestionById(this.paperId)
            .then((res) => {
              let questionList = res.data;
              this.assemblyQuestions(paperQuestionInfo, questionList);
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
        })
        .catch(() => {
          this.loading = false;
        });
    },
    assemblyQuestions(paperQuestion, questionList) {
      console.log(paperQuestion, questionList);
      this.paperData = paperQuestion.map((item) => {
        let options = { ...item, optionId: guid() };
        let targetList = [];
        item.questions.forEach((cItem) => {
          let currQuestion = questionList.find((qItem) => {
            return qItem.questionId === cItem.questionId;
          });
          if (currQuestion) {
            targetList.push({ ...currQuestion, ...cItem, optionId: guid() });
          }
        });
        options["questions"] = targetList;
        return options;
      });

      this.checkHeader();
      //console.log(this.paperData);
    },
    swapArr(arr, index1, index2) {
      arr[index1] = arr.splice(index2, 1, arr[index1])[0];
      return arr;
    },
    handleEdit({ pIndex, cIndex }) {
      //console.log('编辑', pIndex, cIndex)
      let currQuestion = this.paperData[pIndex].questions[cIndex];
      //console.log(currQuestion)
      this.$refs.editDialog.open(currQuestion.questionId)
    },
    handleMoveUp({ pIndex, cIndex }) {
      this.swapArr(this.paperData[pIndex].questions, cIndex, cIndex - 1);
    },
    handleMoveDown({ pIndex, cIndex }) {
      this.swapArr(this.paperData[pIndex].questions, cIndex, cIndex + 1);
    },
    handleDelete({ pIndex, cIndex }) {
      this.paperData[pIndex].questions.splice(cIndex, 1);
      // console.log(this.paperData[pIndex])
      // 处理删除后的数据
      this.paperData.map((item, index) => {
        if (item.questions.length > 0) {
          if (index === pIndex) {
            let questionsLength = item.questions.length;
            let totalScore = item.questions.reduce((prev, cur) => {
              return prev + cur.score;
            }, 0);

            item.score = totalScore;
            this.$set(item, "bigDesc", `(本大题共${questionsLength}小题，共${totalScore}分)`);
          }
        } else {
          this.paperData.splice(index, 1);
        }
      });
      this.$forceUpdate();
      this.checkHeader();
    },
    confirmEditQuestion(data) {
      for (let i = 0; i < this.paperData.length; i++) {
        let item = this.paperData[i];
        for (let j = 0; j < item.questions.length; j++) {
          let cItem = item.questions[j];
          if (cItem.questionId === data.questionId) {
            cItem.questionSubject = data.questionSubject;
            cItem.questionContent = data.questionContent;
            break;
          }
        }
      }
    },
    openProblem() {
      this.$refs.paperProblem.open();
    },
    confirmPaper(data) {
      for (let i = 0; i < data.length; i++) {
        this.addPaper(data[i]);
      }
    },
    addPaper(data) {
      let currTypeIndex = this.paperData.findIndex((item) => {
        return item.questionType === data.questionType;
      });

      if (!data.score) {
        data.score = 1;
      }

      data["optionId"] = guid();

      if (currTypeIndex === -1) {
        this.paperData.push({
          bigName: this.dict.label.topic_type[data.questionType],
          bigDesc: `(本大题共${1}小题，共${data.score}分)`,
          questionType: data.questionType,
          questions: [data],
          optionId: guid(),
        });
      } else {
        let currBigPaper = this.paperData[currTypeIndex];
        let questionIndex = currBigPaper.questions.findIndex((item) => {
          return item.questionId === data.questionId;
        });
        if (questionIndex === -1) {
          currBigPaper.questions.push(data);
        }

        let questionsLength = currBigPaper.questions.length;
        let totalScore = currBigPaper.questions.reduce((prev, cur) => {
          return prev + cur.score;
        }, 0);
        currBigPaper["bigDesc"] = `(本大题共${questionsLength}小题，共${totalScore}分)`;
      }
    },
    savePaper() {
      let totalScore = 0;
      let paperQuestion = this.paperData.map((item) => {
        let options = { ...item };
        let questions = item.questions.map((cItem) => {
          totalScore = totalScore + cItem.score;
          return {
            questionId: cItem.questionId,
            score: cItem.score,
            questionType: cItem.questionType,
            questionEasy: cItem.questionEasy,
          };
        });
        options.questions = questions;
        return options;
      });

      let option = {
        paperName: this.paperDetail.paperName,
        paperDes: this.paperDetail.paperDes,
        paperAttention: this.paperDetail.paperAttention,
        paperSealLine: "1", // 是否有密封线
        paperTotalScore: totalScore,
        paperTime: this.paperDetail.paperTime,
        paperEndTime: "20",
        paperQuestionInfo: JSON.stringify(paperQuestion),
        courseId: this.cascader.treeNode.id,
      };

      if (this.isEdit) {
        updateJuanPaper({
          paperId: this.paperId,
          ...option,
        })
          .then((res) => {
            this.$message({
              message: "试卷修改",
              type: "success",
            });
            setTimeout(() => {
              this.$router.push("/juanGenerate/juanPaper/index");
            }, 1000);
          })
          .catch();
      } else {
        addJuanPaper(option)
          .then((res) => {
            this.$message({
              message: "试卷创建成功",
              type: "success",
            });
            setTimeout(() => {
              this.$router.push("/juanGenerate/juanPaper/index");
            }, 1000);
          })
          .catch();
      }
    },

    changeSelection(optionId) {
      this.attrData = null;
      this.paperType = "";
      for (let i = 0; i < this.paperData.length; i++) {
        let item = this.paperData[i];
        if (item.optionId === optionId) {
          this.attrData = item;
          this.paperType = "bigQuestion";
          break;
        }
        for (let j = 0; j < item.questions.length; j++) {
          let cItem = item.questions[j];
          if (cItem.optionId === optionId) {
            this.attrData = cItem;
            this.paperType = "question";
            break;
          }
        }
      }
    },
    changeQuestionAttr(data) {
      console.log(data);
      for (let i = 0; i < this.paperData.length; i++) {
        let item = this.paperData[i];
        if (item.optionId === data.optionId) {
          for (const key in data.attrs) {
            this.$set(item, key, data.attrs[key]);
          }
          break;
        }
        for (let j = 0; j < this.paperData.length; j++) {
          let cItem = item.questions[j];
          if (cItem.optionId === data.optionId) {
            for (const key in data.attrs) {
              this.$set(cItem, key, data.attrs[key]);

              if (key === "score") {
                let questionsLength = item.questions.length;
                let totalScore = item.questions.reduce((prev, cur) => {
                  return prev + cur.score;
                }, 0);
                this.$set(item, "bigDesc", `(本大题共${questionsLength}小题，共${totalScore}分)`);
              }
            }
            break;
          }
        }
      }
    },
    checkHeader() {
      this.attrData = this.paperDetail;
      this.paperType = "paperHeader";
    },
    changePaperAttr(data) {
      for (const key in data) {
        this.$set(this.paperDetail, key, data[key]);
      }
    },
    downloadPaper() {
      this.download("juan/juanPaperBakeup/exportPaper/" + this.paperId, {}, this.paperDetail.paperName + `.docx`);
    },
    downloadAnswer() {
      this.download("juan/juanPaperBakeup/exportPaperAnswer/" + this.paperId, {}, this.paperDetail.paperName + `答案.docx`);
    },
  },
};
</script>

<style lang="scss" scoped>
.paper-detail {
  position: relative;
  width: 100%;
  height: calc(100vh - 50px);
  background-color: #f4f4f8;
  padding: 20px;
  box-sizing: border-box;

  .paper-right {
    height: 100%;
    display: flex;
    flex-direction: column;

    .tools-bar {
      flex-shrink: 0;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .paper-content {
      flex: 1;
      height: 0;
      margin-top: 10px;
      display: flex;
      justify-content: space-between;

      .paper-view,
      .paper-attr {
        position: relative;
        border-radius: 8px;
        display: flex;
        flex-direction: column;

        .paper-title {
          width: 100%;
          height: 46px;
          background-color: #ebedf2;
          font-size: 16px;
          color: #282f47;
          font-weight: bold;
          padding-left: 24px;
          box-sizing: border-box;
          display: flex;
          align-items: center;
          border-radius: 8px 8px 0 0;

          &::before {
            content: "";
            width: 2px;
            height: 15px;
            display: block;
            background-color: #1890ff;
            margin-right: 5px;
          }
        }

        .paper-body {
          width: 100%;
          flex: 1;
          height: 0;
          background-color: #fff;
          overflow-y: auto;
        }
      }

      .paper-view {
        flex: 1;
        width: 0;
      }

      .paper-attr {
        margin-left: 24px;
        width: 360px;
        flex-shrink: 0;
      }
    }
  }
}

.hasTagsView {
  .paper-detail {
    height: calc(100vh - 84px);
  }
}

.not-click {
  pointer-events: none;
}
</style>
